/**
 * Created by zhoulin on 2019/3/31.
 */
$(function () {
    //查询菜单模块
    //ajax(0)
})
var schoolMap = new Map();
var app = new Vue({
    el: '#wrapper',
    data: {
        iframeSrc:"home1.html",
        toggleIndex:0,
        companyText:"切换机构单位",
        userInfo:{username:"",nickname:""},
        menuList:[{id:"1",icon:"fa fa-refresh",name:"系统权限加载中",pid:"0",url:"../login.html",children:[]}],
        companyList:[{id:"1",name:"机构加载中"}],
        deptPermList:[{id:"1",type:"1",name:"二级单位加载中",schoolId:"0"}],
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if(empty(token)){
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon:5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            },1200)

            return ;
        }

        //查询登录人信息
        that.getUserInfo();
        //初始化机构查询
        that.getCompanyInfo(0);

    },
    methods: {
        // 修改密码
        updateWp: function() {
            layer.open({
                type: 1,
                title: '修改密码',
                area: ['500px','300px'],
                content: $('#updatePasswd')
            });
        },
        // 确定
        submitPwd: function() {
            var that = this;
            var oldPassword = $('input[name="oldPassword"]').val();
            if (empty(oldPassword)) {
                layer.msg('请输入原始密码', {time: 1500, icon: 5});
                return;
            }
            var password = $('input[name="password"]').val();
            if (empty(password)) {
                layer.msg('请输入新的密码', {time: 1500, icon: 5});
                return;
            }
            var confirmPassword = $('input[name="confirmPassword"]').val();
            if (empty(confirmPassword)) {
                layer.msg('请输入确认密码', {time: 1500, icon: 5});
                return;
            }
            if (password != confirmPassword) {
                layer.msg('新密码与确认密码不匹配！', {time: 1500, icon: 5});
                return;
            }
            Post(that, _HOST + _API.business_manage_index_updatePs + "?oldPassword=" + oldPassword + "&password=" + password, {}, true, '')
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            layer.closeAll();
                            layer.msg(response.msg, {time: 1500, icon: 1});
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                });
        },
        //退出登录
        loginOut:function () {
            layer.msg('确认退出登录？', {
                time: 0 //不自动关闭
                ,shade: 0.5
                ,btn: ['退出', '取消']
                ,yes: function(index){
                    /*sessionStorageUtils.del(storageKey.sessionStorageKey.token);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.permCodes);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.schoolId);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.companyId);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.deptId);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.uploadFile.requstUrl);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.schoolMap);*/
                    sessionStorage.clear();
                    layer.close(index);
                    //加载层-风格4
                    var load = layer.msg('退出中。。。', {
                        time: 0 //不自动关闭
                        ,icon: 16
                        ,shade: 0.5
                    });

                    setTimeout(function () {
                        layer.close(load);
                        window.location.href = _LOGIN_PAGE;
                    },1500)
                }
            });
        },
        //获取用户基本信息
        getUserInfo:function () {
            var that = this;
            Get(that,_HOST+_API.business_manage_sysBusiness_getUserInfo)
                .then(function (response) {
                    // 响应成功回调
                    //console.log(response)
                    if(response){
                        if(response.success){
                            //layer.msg("查询成功！");
                            that.userInfo = response.data;
                            console.log(that.userInfo)
                            if(1 == that.userInfo.type){
                                that.iframeSrc = "home.html";
                            }
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        //查询菜单目录
        getMenu:function (pid) {
            var that = this;
            var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
            var deptId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.deptId);
            Get(that,_HOST+_API.business_manage_index_getMenu+pid+"/"+companyId+"/"+deptId)
                .then(function (response) {
                    // 响应成功回调
                    //console.log(response)
                    if(response){
                        if(response.success){
                            //layer.msg("查询成功！");
                            if(0 == pid){
                                that.menuList = response.list;
                                if(that.menuList.length > 0){
                                    that.getMenu(that.menuList[0].id);
                                }
                                //ajax(that.menuList[0].id);
                            }else {
                                li(response.list)
                            }
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        //获取机构信息
        getCompanyInfo:function (companyId) {
            var that = this;
            that.deptPermList = [];
            Get(that,_HOST+_API.business_manage_index_getCompanyInfo+companyId)
                .then(function (response) {
                    // 响应成功回调
                    if(response){
                        if(response.success){
                            //layer.msg("查询成功！");
                            if(0 == companyId){
                                that.companyList = response.data.companyMapList;
                            }
                            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.companyId,companyId);
                            that.deptPermList = response.data.deptPermList;
                            console.log(that.deptPermList)
                            if(0 == companyId){
                                if(that.deptPermList.length > 0){
                                    for (dept of that.deptPermList){
                                        if(dept.type == 1){
                                            schoolMap.set(dept.schoolId,dept.name);
                                        }
                                    }
                                    sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.schoolMap,MapToObj(schoolMap));
                                    if(that.deptPermList[0].type == 1){
                                        sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.schoolId,that.deptPermList[0].schoolId);
                                    }else {
                                        sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.schoolId,"");
                                    }
                                    sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.companyId,that.deptPermList[0].companyId);
                                    sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.deptId,that.deptPermList[0].id);
                                    that.companyText = that.deptPermList[0].name;
                                    that.authorizedLogin(that.deptPermList[0].companyId,that.deptPermList[0].id);
                                }
                            }else {
                                creatDeptLi(that.deptPermList)
                            }

                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        //授权登录
        authorizedLogin:function (companyId,deptId) {
            var that = this;
            that.menuList = [];
            Get(that,_HOST+_API.business_manage_index_authorizedLogin+companyId+"/"+deptId)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response)
                    if(response){
                        if(response.success){
                            that.menuList = response.menuList;
                            //console.log(that.menuList)
                            if(that.menuList.length > 0){
                                that.toggleIndex = 0;
                                that.getMenu(that.menuList[0].id);
                            }
                            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.token,response.token);
                            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.permCodes,response.permCodes);
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        toggle:function (id,index) {
            var that = this;
            that.toggleIndex = index;
            that.getMenu(id);
            //ajax(id);
        },
        changeCompany:function () {
            var that = this;
            var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
            var deptId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.deptId);
/*            var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);
            console.log(schoolMap)
            console.log(schoolMap["6"])
            console.log(schoolMap["7"])*/
            var htmlStr = "<div style='width: 100%;'>";

            htmlStr += "<ul class='list-group list-group-left'>"
            for (company of that.companyList){
                htmlStr+="<li onclick='companyClick(this)' data-id='"+company.id+"' class='list-group-item "+(company.id == companyId ? "list-group-item-active" : "")+"'>"+company.name+"</li>";
            }
            htmlStr+="</ul>";

            htmlStr += "<ul class='list-group list-group-right' id='deptPermList'>"
            for (var i=0;i<that.deptPermList.length;i++){
                htmlStr+="<li onclick='deptClick(this)' data-index='"+i+"' data-id='"+that.deptPermList[i].id+"' class='list-group-item "+(that.deptPermList[i].id == deptId ? "list-group-item-active" : "")+"'>"+that.deptPermList[i].name+"</li>";
            }
            htmlStr+="</ul>";
            htmlStr += "</div>"
            //页面层
            parent.layer.open({
                title:"机构单位切换",
                type: 1,
                area: ['420px', '420px'], //宽高
                content: htmlStr
            });
        }
    },
})

function submitPWD() {
    app.submitPwd();
}

/**
 * 机构点击事件
 * @param that
 */
function companyClick(that) {
    $(that).siblings('li').removeClass('list-group-item-active');  // 删除其他兄弟元素的样式
    $(that).addClass("list-group-item-active");
    var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
    if($(that).attr("data-id") != companyId){
        $("#deptPermList>li").remove();
        app.getCompanyInfo($(that).attr("data-id"));
    }
}
function creatDeptLi(deptPermList) {
    var deptId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.deptId);
    var htmlStr = "";
    for (var i=0;i<deptPermList.length;i++){
        if(deptPermList[i].type == 1){
            schoolMap.set(deptPermList[i].schoolId,deptPermList[i].name);
        }
        htmlStr+="<li onclick='deptClick(this)' data-index='"+i+"' data-id='"+deptPermList[i].id+"' class='list-group-item "+(deptPermList[i].id == deptId ? "list-group-item-active" : "")+"'>"+deptPermList[i].name+"</li>";
    }
    $("#deptPermList").append(htmlStr)
}
/**
 * 机构单位点击事件
 * @param that
 */
function deptClick(that) {
    $(that).siblings('li').removeClass('list-group-item-active');  // 删除其他兄弟元素的样式
    $(that).addClass("list-group-item-active");
    var deptId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.deptId);
    if($(that).attr("data-id") != deptId){
        $(".J_tabCloseAll").click();
        var index = $(that).attr("data-index");
        if(app.deptPermList.length > 0){
            if(app.deptPermList[index].type == 1){
                sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.schoolId,app.deptPermList[index].schoolId);
            }else {
                sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.schoolId,"");
            }
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.schoolMap,MapToObj(schoolMap));
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.companyId,app.deptPermList[index].companyId);
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.deptId,app.deptPermList[index].id);
            $("#side-menu>li").nextAll().remove();
            app.companyText = app.deptPermList[index].name;
            parent.layer.closeAll();
            app.authorizedLogin(app.deptPermList[index].companyId,app.deptPermList[index].id);
        }
    }
}

/**
 * 动态构建权限菜单
 * @param list
 */
function li(list) {
    $("#side-menu>li").nextAll().remove();
    var liHtml = ''
    for (var i = 0; i<list.length;i++){
        liHtml = liHtml + '<li><a class="'+(list[i].children.length>0 ? '' : 'J_menuItem')+'" href="'+(list[i].children.length>0 ? 'javascript:;' : list[i].url)+'" onclick="clickMenuChildren(this)"><i class="'+list[i].icon+'"></i><span class="nav-label">'+list[i].name+'</span>';
        if(list[i].children.length > 0 ){
            liHtml = liHtml + '<span class="fa arrow"></span></a><ul class="nav nav-second-level collapse">';
            for (var j = 0; j<list[i].children.length;j ++){
                liHtml = liHtml + '<li><a class="J_menuItem" href="'+list[i].children[j].url+'"><i class="'+list[i].children[j].icon+'"></i>'+list[i].children[j].name+'</a></li>'
            }
            liHtml = liHtml + '</ul>'

        }else {
            liHtml = liHtml + '</a>';
        }
        liHtml = liHtml+'</li>';
    }
    $("#side-menu").append(liHtml)
    new_element=document.createElement("script");
    new_element.setAttribute("type","text/javascript");
    new_element.setAttribute("src","../../../public-tools/pc/js/contabs.min.js");
    document.body.appendChild(new_element);
}

/**
 * 菜单点击样式跟换
 * @param that
 */
function clickMenuChildren(that) {
    $(that).parent("li").siblings('li').removeClass('active');  // 删除其他兄弟元素的样式
    $(that).parent("li").siblings('li').children("ul").removeClass('in');  // 删除其他兄弟元素的样式
    $(that).next("ul").addClass('in');  // 删除其他兄弟元素的样式
    if($(that).parent("li").hasClass("active")){
        $(that).parent("li").removeClass("active");
        $(that).next("ul").removeClass('in');  // 删除其他兄弟元素的样式
    }else{
        $(that).parent("li").addClass("active");
    }
}

/**
 * 备用
 * @param pid
 */
function ajax(pid) {
    var index = layer.load();
    $.ajax({
        async: true,
        url: _HOST+_API.admin_index_getMenu+pid,
        type: "get",
        dataType: 'json',
        headers:{Authorization:sessionStorageUtils.getJson(storageKey.sessionStorageKey.token)},
        success: function (data) {
            layer.close(index);
            if (data.success) {
                console.log(data);
                if(0 == pid){
                    app.menuList = data.list;
                    //that.getMenu(that.menuList[0].id);
                    ajax(app.menuList[0].id);
                }else {
                    li(data.list)
                }
            }
        }
    });
}
